package com.aiti.lulian.controller.crm;

import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.controller.WebController;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.dto.crm.CrmFollowRecordDto;
import com.aiti.lulian.entity.crm.CrmFollowRecord;
import com.aiti.lulian.entity.excel.CrmFollowRecordExcelExport;
import com.aiti.lulian.handler.HeaderStyleHandler;
import com.aiti.lulian.service.ICrmFollowRecordService;
import com.aiti.lulian.vo.crm.CrmFollowRecordVo;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.net.HttpHeaders;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Api(tags = "CRM跟进记录控制层")
@RequestMapping("/crm/follow")
public class CrmFollowRecordController extends WebController<CrmFollowRecord> {

    @Autowired
    private ICrmFollowRecordService crmFollowRecordService;

    @ApiOperation("写跟进")
    @PostMapping("/write")
    public Message writeFollowRecord(@RequestBody CrmFollowRecordDto dto) {
        String userId = dto.getUserId();
        if (StrUtil.isBlank(userId)) {
            userId = findUserId();
            if (StrUtil.isBlank(userId)) {
                return Fail("请先登录");
            }
        }
        dto.setCreator(userId);
        return crmFollowRecordService.writeFollowRecord(dto);
    }

    @ApiOperation("查询跟进记录列表")
    @GetMapping("/list")
    public Message getFollowRecordList(CrmFollowRecordDto dto) {
        String userId = dto.getUserId();
        if (StrUtil.isBlank(userId)) {
            userId = findUserId();
            if (StrUtil.isBlank(userId)) {
                return Fail("请先登录");
            }
            dto.setUserId(userId);
        }
        Integer pageNum = dto.getPageNum();
        Integer pageSize = dto.getPageSize();
        Page<CrmFollowRecord> page = startPage(pageNum, pageSize);
        List<CrmFollowRecordVo> followRecordVoList = crmFollowRecordService.getFollowRecordList(dto, page);
        return Success(getPageResult(followRecordVoList, pageNum, pageSize, page.getTotal()));
    }

    @ApiOperation("删除跟进记录")
    @PostMapping("/delete")
    public Message deleteFollowRecord(@RequestBody CrmFollowRecordDto dto) {
        String userId = dto.getUserId();
        if (StrUtil.isBlank(userId)) {
            userId = findUserId();
            if (StrUtil.isBlank(userId)) {
                return Fail("请先登录");
            }
        }
        return crmFollowRecordService.deleteFollowRecord(dto);
    }

    @ApiOperation("导出跟进记录")
    @GetMapping("/export")
    public Message exportFollowRecord(CrmFollowRecordDto dto,
                                      HttpServletResponse response) {
        String userId = dto.getUserId();
        if (StrUtil.isBlank(userId)) {
            userId = findUserId();
            if (StrUtil.isBlank(userId)) {
                return Fail("请先登录");
            }
            dto.setUserId(userId);
        }
        List<CrmFollowRecordVo> followRecordList = crmFollowRecordService.getFollowRecordList(dto, null);
        //准备要导出的数据列表
        List collect = followRecordList.stream().map(i -> {
            CrmFollowRecordExcelExport crmFollowRecordExcelExport = new CrmFollowRecordExcelExport();
            BeanUtils.copyProperties(i, crmFollowRecordExcelExport);
            return crmFollowRecordExcelExport;
        }).collect(Collectors.toList());

        // 设置响应头，确保浏览器以下载方式处理文件
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        try {
            // 设置文件名，注意需要对中文进行 URL 编码
            String fileName = URLEncoder.encode("跟进记录", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                    "attachment; filename=\"" + fileName + ".xlsx\";" +
                            " filename*=UTF-8''" + fileName + ".xlsx");

            // 使用 EasyExcel 写入数据到输出流
            OutputStream outputStream =  response.getOutputStream();
            EasyExcel.write(outputStream, CrmFollowRecordExcelExport.class)
                    .sheet("跟进记录")
                    .registerWriteHandler(new HeaderStyleHandler())
                    .doWrite(collect);

            // 关闭流资源
            if (outputStream != null) {
                outputStream.close();
            }

            return Success();
        } catch (IOException e) {
            logger.error("导出异常：===》" + e);
            return Fail(e.getMessage());
        }
    }
}